package com.dd.lnetwork

import okhttp3.Interceptor
import okhttp3.Response

class TokenInterceptor(
    private var deviceId: String,
    private var token: String?,
    private var cookies: HashSet<String>?
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val requestBuilder = originalRequest.newBuilder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Device-OS", "Android")
            .addHeader("User-Agent", "User-Agent")
            .method(originalRequest.method, originalRequest.body)


        requestBuilder.addHeader("Device-Id", deviceId)

        token?.let {
            requestBuilder.addHeader("x-user-token", it)
        }

        cookies?.forEach {
            var cookie = ""
            // 保证 cookie 中 x-user-token 与 本地 token 一致 ，健壮性处理
            if (it.contains("x-user-token=;") && !token.isNullOrEmpty()) {
                cookie = it.replace("x-user-token=;", String.format("x-user-token=%s;", token))
            }
            requestBuilder.addHeader("Cookie", cookie)
        }

        val request = requestBuilder.build()
        return chain.proceed(request)
    }
}